import sqlite3
import os

# 获取项目根目录
project_root = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(project_root, 'database.db')

# 如果数据库文件不存在，则创建它
if not os.path.exists(db_path):
    print(f"数据库文件 {db_path} 不存在，将创建新的数据库文件")
    conn = sqlite3.connect(db_path)
    conn.close()

# 连接到数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()

# 检查sessions表是否存在
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'")
table_exists = cursor.fetchone()

if not table_exists:
    print("sessions表不存在，需要初始化数据库")
else:
    # 检查category列是否存在
    cursor.execute("PRAGMA table_info(sessions)")
    columns = cursor.fetchall()
    column_names = [column[1] for column in columns]
    
    if 'category' not in column_names:
        print("添加category列到sessions表")
        try:
            cursor.execute("ALTER TABLE sessions ADD COLUMN category VARCHAR(20) DEFAULT 'default'")
            conn.commit()
            print("成功添加category列")
        except Exception as e:
            print(f"添加category列失败: {e}")
    else:
        print("category列已存在")

conn.close()